package cn.commander.shiro.realms;

import cn.commander.service.SysUserService;
import cn.commander.shiro.entity.SysUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * realm实现类,用于实现具体的验证和授权方法
 *
 * @author Bean
 */
public class MyShiroRealm extends AuthorizingRealm {
	private static final Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);
	@Autowired
	private SysUserService sysUserService;

	/**
	 * 方面用于加密 参数：AuthenticationToken是从表单穿过来封装好的对象
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		logger.info("doGetAuthenticationInfo:{}", token);
		// 将AuthenticationToken强转为AuthenticationToken对象
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;

		// 获得从表单传过来的用户名
		String username = upToken.getUsername();

		// 从数据库查看是否存在用户
		// 如果用户不存在，抛此异常
		SysUser sysUser = sysUserService.selectUsername(username);
		if (sysUser == null) {
			throw new UnknownAccountException("无此用户名！");
		}
		Object credentials = token.getCredentials();
		if (credentials == null) {
			throw new UnknownAccountException("账号或密码不正确");
		}
		String password = new String((char[]) credentials); //得到密码
		// 密码错误
//		if (!MD5Utils.generatePasswordMD5(password, sysUser.getSalt()).equals(sysUser.getPassword())) {
//			throw new IncorrectCredentialsException("账号或密码不正确");
//		}
		// 账号锁定
		if ("N".equals(sysUser.getValid())) {
			throw new LockedAccountException("账号已被锁定,请联系管理员");
		}
		//principal 认证的实体信息，可以是username，也可以是用户的实体类对象
//		credentials = sysUser.getPassword();
		// 创建SimpleAuthenticationInfo对象，并且把username和password等信息封装到里面
		// 用户密码的比对是Shiro帮我们完成的
		// 盐值加密的盐
		ByteSource credentialsSalt = ByteSource.Util.bytes(sysUser.getUsername());
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUser.getUsername(), sysUser.getPassword(), credentialsSalt, getName());

		return info;
	}

	// 用于授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// 从PrincipalCollection中获得用户信息
		Object principal = principals.getPrimaryPrincipal();
		logger.info("ShiroRealm  AuthorizationInfo:{}", principal.toString());
		// 根据用户名来查询数据库赋予用户角色,权限（查数据库）
		Set<String> roles = new HashSet<>();
		Set<String> permissions = new HashSet<>();
		roles.add("user");
		permissions.add("user:query");
		if ("admin".equals(principal)) {
			roles.add("admin");
			permissions.add("admin:query");
		}

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
		//添加权限
		info.setStringPermissions(permissions);
		return info;
	}

}